//
//  EtatConsultationController.m
//  Cabinet
//
//  Created by Florent Montsegur on 27/05/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "EtatConsultationController.h"
#import "Consultation.h"
#import "Person.h"
#import "CabinetDefines.h"
#import "ConsultationViewController.h"

@implementation EtatConsultationController

@synthesize mManagedObjectContext;
@synthesize mConsultationEntity;
@synthesize mStartDate;
@synthesize mEndDate;
@synthesize mPaiment;
@synthesize mConsultationView;
@synthesize mMessage;
@synthesize mTotal;
@synthesize mPayeeToutes;
@synthesize mPayees;
@synthesize mImpayees;


- (id)initWithWindow:(NSWindow *)window
{
    self = [super initWithWindow:window];
    if (self) {
        // Initialization code here.
    }
    
    return self;
}


- (NSString*)windowNibName
{
	return @"EtatConsult";
}


- (void)windowDidLoad
{
    [super windowDidLoad];
    
    [[self mConsultationView] setTarget:self];
    [[self mConsultationView] setDoubleAction:@selector(consultationDoubleClickAction:)];
    
    NSString *start = [[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d 00:00:00 +200" timeZone:nil locale:[[NSUserDefaults standardUserDefaults]dictionaryRepresentation]];
    NSDate *startDate = [NSDate dateWithString:start];
    NSDate *endDate = [startDate dateByAddingTimeInterval:((NSTimeInterval)60*60*24)];

    // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
    [[self mStartDate] setDateValue:startDate];
    [[self mEndDate] setDateValue:endDate];
    
    [self rechercher];
}

- (IBAction)rechercherAction:sender
{
    [self rechercher];    
}

- (void) rechercher
{
    [mMessage setStringValue:@"Aucun acte trouvé"];
    
    if( ([self mManagedObjectContext] == nil) || ([self mConsultationEntity] == nil) )
        return;
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:mConsultationEntity];
    
    [request setPredicate:[self getPredicate]];
    
    
    mConsultations = [[self mManagedObjectContext] executeFetchRequest:request error:nil];
    
    if(mConsultations == nil)
        return;
    
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"CreationDate" ascending:NO];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    
    mConsultations = [mConsultations sortedArrayUsingDescriptors:sortDescriptors];
    
    NSInteger nbItems = [self count];
    int total = 0;
    
    for( NSInteger i=0; i<nbItems; i++)
    {
        Consultation *c = [mConsultations objectAtIndex:i];
        if(c != nil)
            total += [[c Somme] intValue];
    }
    
    
    [mConsultationView reloadData];
    
    [mMessage setStringValue:[NSString stringWithFormat:@"%ld actes", nbItems]];
    [mTotal setStringValue:[NSString stringWithFormat:@"%d €",total]];
}

- (NSPredicate*) getPredicate
{
    NSMutableString *format =  [[NSMutableString alloc] initWithString:@"(CreationDate >= %@) AND (CreationDate < %@)"];
    
    if( [[self mPayees] intValue] == 1 )
        [format appendString:@" AND Paye = true"];
    else if( [[self mImpayees] intValue] == 1 )
        [format appendString:@" AND Paye = false"];
    
    NSString *paiement = [mPaiment stringValue];
    if( (paiement != nil) && ([paiement length]>0) )
        [format appendFormat:@" AND (Payement = '%@')", paiement];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:format, [[self mStartDate] dateValue], [[self mEndDate] dateValue]];
    
    return predicate;
}

- (NSInteger) count{
    if( mConsultations == nil)
        return 0;
    
    return [mConsultations count];
}

- (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
{    
    return [self count];
}

- (NSString*)getFeuille:(NSNumber*)aValue
{
    if([aValue intValue] == FeuilleGardee )
        return @"Gardée";
    
    if([aValue intValue] == FeuilleDonnee )
        return @"Donnée";
    
    return @"Non faite";
}

- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex{
    
    if( rowIndex >= [self count])
        return @"";

    Consultation *cons = [mConsultations objectAtIndex:rowIndex];
    if (cons == nil)
        return @"";
    
    if( [[aTableColumn identifier] caseInsensitiveCompare:@"date"] == NSOrderedSame )
        return [[cons CreationDate] descriptionWithCalendarFormat:@"%d/%m/%y %H:%M" timeZone:nil locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]];
    
    if( [[aTableColumn identifier] caseInsensitiveCompare:@"nom"] == NSOrderedSame )
        return [[cons Person] Nom];
    
    if( [[aTableColumn identifier] caseInsensitiveCompare:@"prenom"] == NSOrderedSame )
        return [[cons Person] Prenom];
    
    if( [[aTableColumn identifier] caseInsensitiveCompare:@"ref"] == NSOrderedSame )
        return [cons Reference];
    
    if( [[aTableColumn identifier] caseInsensitiveCompare:@"diag"] == NSOrderedSame )
        return [cons Diagnostic];
    
    if( [[aTableColumn identifier] caseInsensitiveCompare:@"acte"] == NSOrderedSame )
        return [cons Acte];
    
    if( [[aTableColumn identifier] caseInsensitiveCompare:@"somme"] == NSOrderedSame )
        return [cons Somme];
    
    if( [[aTableColumn identifier] caseInsensitiveCompare:@"paiment"] == NSOrderedSame )
        return [cons Payement];
    
    if( [[aTableColumn identifier] caseInsensitiveCompare:@"feuille"] == NSOrderedSame )
        return [self getFeuille:[cons EtatFeuille]];
    
    if( [[aTableColumn identifier] caseInsensitiveCompare:@"paye"] == NSOrderedSame )
        return ([[cons Paye] intValue] == 1 ? @"Oui" : @"Non");
    
    return @"";
}

- (IBAction)consultationDoubleClickAction:(id)sender
{
    [self modifierAction:sender];
}


- (Consultation*)getConsultationAtIndex:(NSInteger)aRowIndex
{
    if(aRowIndex<0) 
        return nil;
    
    if(aRowIndex>=[self count]) 
        return nil;
    
    return [mConsultations objectAtIndex:aRowIndex];
}

- (IBAction)modifierAction:sender
{
    NSInteger row =  [mConsultationView selectedRow];
    Consultation * selectedCons = [self getConsultationAtIndex:row];
    if(selectedCons == nil)
        return;
    
    mConsultationWnd = [[ConsultationViewController alloc] init];
    [mConsultationWnd setConsultation:selectedCons];
    [mConsultationWnd showWindow:nil];
}

- (IBAction)supprimerAction:sender
{
    NSInteger row =  [mConsultationView selectedRow];
    Consultation * selectedCons = [self getConsultationAtIndex:row];
    if(selectedCons == nil)
        return;
    
    NSAlert * alert = [NSAlert alertWithMessageText:@"Attention"
                                 defaultButton:@"Supprimer"
                              alternateButton:@"Annuler"
                                  otherButton:nil
                    informativeTextWithFormat:[NSString stringWithFormat:@"La consultation de %@ %@ du %@ sera supprimée définitivement", [[selectedCons Person] Prenom], [[selectedCons Person] Nom], [[selectedCons CreationDate] descriptionWithCalendarFormat:@"%d/%m/%y" timeZone:nil locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]] ]];
    
    // should we try again?
    if ([alert runModal] == NSOKButton)
    {
        [[self mManagedObjectContext] deleteObject:selectedCons];
        
        NSLog(@"Supprimée !!");
        [self rechercher];
    }
}

@end
